home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / share / automake-1.5 / Automake / Struct.pm
Encoding:
Perl POD Document  |  2005-10-16  |  18.1 KB  |  601 lines

  1. # automake - create Makefile.in from Makefile.am
  2. # Copyright 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
  3. # Free Software Foundation, Inc.
  4.  
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2, or (at your option)
  8. # any later version.
  9.  
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14.  
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  18. # 02111-1307, USA.
  19.  
  20. # Originally written by David Mackenzie <djm@gnu.ai.mit.edu>.
  21. # Perl reimplementation by Tom Tromey <tromey@cygnus.com>.
  22.  
  23. package Automake::Struct;
  24.  
  25. ## See POD after __END__
  26.  
  27. use 5.005;
  28.  
  29. use strict;
  30. use vars qw(@ISA @EXPORT $VERSION);
  31.  
  32. use Carp;
  33.  
  34. require Exporter;
  35. @ISA = qw(Exporter);
  36. @EXPORT = qw(struct);
  37.  
  38. $VERSION = '0.58';
  39.  
  40. ## Tested on 5.002 and 5.003 without class membership tests:
  41. my $CHECK_CLASS_MEMBERSHIP = ($] >= 5.003_95);
  42.  
  43. my $print = 0;
  44. sub printem {
  45.     if (@_) { $print = shift }
  46.     else    { $print++ }
  47. }
  48.  
  49. {
  50.     package Class::Struct::Tie_ISA;
  51.  
  52.     sub TIEARRAY {
  53.         my $class = shift;
  54.         return bless [], $class;
  55.     }
  56.  
  57.     sub STORE {
  58.         my ($self, $index, $value) = @_;
  59.         Class::Struct::_subclass_error();
  60.     }
  61.  
  62.     sub FETCH {
  63.         my ($self, $index) = @_;
  64.         $self->[$index];
  65.     }
  66.  
  67.     sub FETCHSIZE {
  68.         my $self = shift;
  69.         return scalar(@$self);
  70.     }
  71.  
  72.     sub DESTROY { }
  73. }
  74.  
  75. sub struct {
  76.  
  77.     # Determine parameter list structure, one of:
  78.     #   struct( class => [ element-list ])
  79.     #   struct( class => { element-list })
  80.     #   struct( element-list )
  81.     # Latter form assumes current package name as struct name.
  82.  
  83.     my ($class, @decls);
  84.     my $base_type = ref $_[1];
  85.     if ( $base_type eq 'HASH' ) {
  86.         $class = shift;
  87.         @decls = %{shift()};
  88.         _usage_error() if @_;
  89.     }
  90.     elsif ( $base_type eq 'ARRAY' ) {
  91.         $class = shift;
  92.         @decls = @{shift()};
  93.         _usage_error() if @_;
  94.     }
  95.     else {
  96.         $base_type = 'ARRAY';
  97.         $class = (caller())[0];
  98.         @decls = @_;
  99.     }
  100.     _usage_error() if @decls % 2 == 1;
  101.  
  102.     # Ensure we are not, and will not be, a subclass.
  103.  
  104.     my $isa = do {
  105.         no strict 'refs';
  106.         \@{$class . '::ISA'};
  107.     };
  108.     _subclass_error() if @$isa;
  109.     tie @$isa, 'Class::Struct::Tie_ISA';
  110.  
  111.     # Create constructor.
  112.  
  113.     croak "function 'new' already defined in package $class"
  114.         if do { no strict 'refs'; defined &{$class . "::new"} };
  115.  
  116.     my @methods = ();
  117.     my %refs = ();
  118.     my %arrays = ();
  119.     my %hashes = ();
  120.     my %classes = ();
  121.     my $got_class = 0;
  122.     my $out = '';
  123.  
  124.     $out = "{\n  package $class;\n  use Carp;\n  sub new {\n";
  125.     $out .= "    my (\$class, \%init) = \@_;\n";
  126.     $out .= "    \$class = __PACKAGE__ unless \@_;\n";
  127.  
  128.     my $cnt = 0;
  129.     my $idx = 0;
  130.     my( $cmt, $name, $type, $elem );
  131.  
  132.     if( $base_type eq 'HASH' ){
  133.         $out .= "    my(\$r) = {};\n";
  134.         $cmt = '';
  135.     }
  136.     elsif( $base_type eq 'ARRAY' ){
  137.         $out .= "    my(\$r) = [];\n";
  138.     }
  139.     while( $idx < @decls ){
  140.         $name = $decls[$idx];
  141.         $type = $decls[$idx+1];
  142.         push( @methods, $name );
  143.         if( $base_type eq 'HASH' ){
  144.             $elem = "{'${class}::$name'}";
  145.         }
  146.         elsif( $base_type eq 'ARRAY' ){
  147.             $elem = "[$cnt]";
  148.             ++$cnt;
  149.             $cmt = " # $name";
  150.         }
  151.         if( $type =~ /^\*(.)/ ){
  152.             $refs{$name}++;
  153.             $type = $1;
  154.         }
  155.         my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
  156.         if( $type eq '@' ){
  157.             $out .= "    croak 'Initializer for $name must be array reference'\n";
  158.             $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
  159.             $out .= "    \$r->$elem = $init [];$cmt\n";
  160.             $arrays{$name}++;
  161.         }
  162.         elsif( $type eq '%' ){
  163.             $out .= "    croak 'Initializer for $name must be hash reference'\n";
  164.             $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
  165.             $out .= "    \$r->$elem = $init {};$cmt\n";
  166.             $hashes{$name}++;
  167.         }
  168.         elsif ( $type eq '$') {
  169.             $out .= "    \$r->$elem = $init undef;$cmt\n";
  170.         }
  171.         elsif( $type =~ /^\w+(?:::\w+)*$/ ){
  172.             $init = "defined(\$init{'$name'}) ? \%{\$init{'$name'}} : ()";
  173.             $out .= "    croak 'Initializer for $name must be hash reference'\n";
  174.             $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
  175.             $out .= "    \$r->$elem = '${type}'->new($init);$cmt\n";
  176.             $classes{$name} = $type;
  177.             $got_class = 1;
  178.         }
  179.         else{
  180.             croak "'$type' is not a valid struct element type";
  181.         }
  182.         $idx += 2;
  183.     }
  184.     $out .= "    bless \$r, \$class;\n  }\n";
  185.  
  186.     # Create accessor methods.
  187.  
  188.     my( $pre, $pst, $sel );
  189.     $cnt = 0;
  190.     foreach $name (@methods){
  191.         if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
  192.             carp "function '$name' already defined, overrides struct accessor method";
  193.         }
  194.         else {
  195.             $pre = $pst = $cmt = $sel = '';
  196.             if( defined $refs{$name} ){
  197.                 $pre = "\\(";
  198.                 $pst = ")";
  199.                 $cmt = " # returns ref";
  200.             }
  201.             $out .= "  sub $name {$cmt\n    my \$r = shift;\n";
  202.             if( $base_type eq 'ARRAY' ){
  203.                 $elem = "[$cnt]";
  204.                 ++$cnt;
  205.             }
  206.             elsif( $base_type eq 'HASH' ){
  207.                 $elem = "{'${class}::$name'}";
  208.             }
  209.             if( defined $arrays{$name} ){
  210.                 $out .= "    my \$i;\n";
  211.                 $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
  212.                 $sel = "->[\$i]";
  213.             }
  214.             elsif( defined $hashes{$name} ){
  215.                 $out .= "    my \$i;\n";
  216.                 $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
  217.                 $sel = "->{\$i}";
  218.             }
  219.             elsif( defined $classes{$name} ){
  220.                 if ( $CHECK_CLASS_MEMBERSHIP ) {
  221.                     $out .= "    croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
  222.                 }
  223.             }
  224.             $out .= "    croak 'Too many args to $name' if \@_ > 1;\n";
  225.             $out .= "    \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
  226.             $out .= "  }\n";
  227.         }
  228.     }
  229.     $out .= "}\n1;\n";
  230.  
  231.     print $out if $print;
  232.     my $result = eval $out;
  233.     carp $@ if $@;
  234. }
  235.  
  236. sub _usage_error {
  237.     confess "struct usage error";
  238. }
  239.  
  240. sub _subclass_error {
  241.     croak 'struct class cannot be a subclass (@ISA not allowed)';
  242. }
  243.  
  244. 1; # for require
  245.  
  246.  
  247. __END__
  248.  
  249. =head1 NAME
  250.  
  251. Class::Struct - declare struct-like datatypes as Perl classes
  252.  
  253. =head1 SYNOPSIS
  254.  
  255.     use Class::Struct;
  256.             # declare struct, based on array:
  257.     struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
  258.             # declare struct, based on hash:
  259.     struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });
  260.  
  261.     package CLASS_NAME;
  262.     use Class::Struct;
  263.             # declare struct, based on array, implicit class name:
  264.     struct( ELEMENT_NAME => ELEMENT_TYPE, ... );
  265.  
  266.  
  267.     package Myobj;
  268.     use Class::Struct;
  269.             # declare struct with four types of elements:
  270.     struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );
  271.  
  272.     $obj = new Myobj;               # constructor
  273.  
  274.                                     # scalar type accessor:
  275.     $element_value = $obj->s;           # element value
  276.     $obj->s('new value');               # assign to element
  277.  
  278.                                     # array type accessor:
  279.     $ary_ref = $obj->a;                 # reference to whole array
  280.     $ary_element_value = $obj->a(2);    # array element value
  281.     $obj->a(2, 'new value');            # assign to array element
  282.  
  283.                                     # hash type accessor:
  284.     $hash_ref = $obj->h;                # reference to whole hash
  285.     $hash_element_value = $obj->h('x'); # hash element value
  286.     $obj->h('x', 'new value');        # assign to hash element
  287.  
  288.                                     # class type accessor:
  289.     $element_value = $obj->c;           # object reference
  290.     $obj->c->method(...);               # call method of object
  291.     $obj->c(new My_Other_Class);        # assign a new object
  292.  
  293.  
  294. =head1 DESCRIPTION
  295.  
  296. C<Class::Struct> exports a single function, C<struct>.
  297. Given a list of element names and types, and optionally
  298. a class name, C<struct> creates a Perl 5 class that implements
  299. a "struct-like" data structure.
  300.  
  301. The new class is given a constructor method, C<new>, for creating
  302. struct objects.
  303.  
  304. Each element in the struct data has an accessor method, which is
  305. used to assign to the element and to fetch its value.  The
  306. default accessor can be overridden by declaring a C<sub> of the
  307. same name in the package.  (See Example 2.)
  308.  
  309. Each element's type can be scalar, array, hash, or class.
  310.  
  311.  
  312. =head2 The C<struct()> function
  313.  
  314. The C<struct> function has three forms of parameter-list.
  315.  
  316.     struct( CLASS_NAME => [ ELEMENT_LIST ]);
  317.     struct( CLASS_NAME => { ELEMENT_LIST });
  318.     struct( ELEMENT_LIST );
  319.  
  320. The first and second forms explicitly identify the name of the
  321. class being created.  The third form assumes the current package
  322. name as the class name.
  323.  
  324. An object of a class created by the first and third forms is
  325. based on an array, whereas an object of a class created by the
  326. second form is based on a hash. The array-based forms will be
  327. somewhat faster and smaller; the hash-based forms are more
  328. flexible.
  329.  
  330. The class created by C<struct> must not be a subclass of another
  331. class other than C<UNIVERSAL>.
  332.  
  333. It can, however, be used as a superclass for other classes. To facilitate
  334. this, the generated constructor method uses a two-argument blessing.
  335. Furthermore, if the class is hash-based, the key of each element is
  336. prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).
  337.  
  338. A function named C<new> must not be explicitly defined in a class
  339. created by C<struct>.
  340.  
  341. The I<ELEMENT_LIST> has the form
  342.  
  343.     NAME => TYPE, ...
  344.  
  345. Each name-type pair declares one element of the struct. Each
  346. element name will be defined as an accessor method unless a
  347. method by that name is explicitly defined; in the latter case, a
  348. warning is issued if the warning flag (B<-w>) is set.
  349.  
  350.  
  351. =head2 Element Types and Accessor Methods
  352.  
  353. The four element types -- scalar, array, hash, and class -- are
  354. represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
  355. optionally preceded by a C<'*'>.
  356.  
  357. The accessor method provided by C<struct> for an element depends
  358. on the declared type of the element.
  359.  
  360. =over
  361.  
  362. =item Scalar (C<'$'> or C<'*$'>)
  363.  
  364. The element is a scalar, and by default is initialized to C<undef>
  365. (but see L<Initializing with new>).
  366.  
  367. The accessor's argument, if any, is assigned to the element.
  368.  
  369. If the element type is C<'$'>, the value of the element (after
  370. assignment) is returned. If the element type is C<'*$'>, a reference
  371. to the element is returned.
  372.  
  373. =item Array (C<'@'> or C<'*@'>)
  374.  
  375. The element is an array, initialized by default to C<()>.
  376.  
  377. With no argument, the accessor returns a reference to the
  378. element's whole array (whether or not the element was
  379. specified as C<'@'> or C<'*@'>).
  380.  
  381. With one or two arguments, the first argument is an index
  382. specifying one element of the array; the second argument, if
  383. present, is assigned to the array element.  If the element type
  384. is C<'@'>, the accessor returns the array element value.  If the
  385. element type is C<'*@'>, a reference to the array element is
  386. returned.
  387.  
  388. =item Hash (C<'%'> or C<'*%'>)
  389.  
  390. The element is a hash, initialized by default to C<()>.
  391.  
  392. With no argument, the accessor returns a reference to the
  393. element's whole hash (whether or not the element was
  394. specified as C<'%'> or C<'*%'>).
  395.  
  396. With one or two arguments, the first argument is a key specifying
  397. one element of the hash; the second argument, if present, is
  398. assigned to the hash element.  If the element type is C<'%'>, the
  399. accessor returns the hash element value.  If the element type is
  400. C<'*%'>, a reference to the hash element is returned.
  401.  
  402. =item Class (C<'Class_Name'> or C<'*Class_Name'>)
  403.  
  404. The element's value must be a reference blessed to the named
  405. class or to one of its subclasses. The element is initialized to
  406. the result of calling the C<new> constructor of the named class.
  407.  
  408. The accessor's argument, if any, is assigned to the element. The
  409. accessor will C<croak> if this is not an appropriate object
  410. reference.
  411.  
  412. If the element type does not start with a C<'*'>, the accessor
  413. returns the element value (after assignment). If the element type
  414. starts with a C<'*'>, a reference to the element itself is returned.
  415.  
  416. =back
  417.  
  418. =head2 Initializing with C<new>
  419.  
  420. C<struct> always creates a constructor called C<new>. That constructor
  421. may take a list of initializers for the various elements of the new
  422. struct.
  423.  
  424. Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
  425. The initializer value for a scalar element is just a scalar value. The
  426. initializer for an array element is an array reference. The initializer
  427. for a hash is a hash reference.
  428.  
  429. The initializer for a class element is also a hash reference, and the
  430. contents of that hash are passed to the element's own constructor.
  431.  
  432. See Example 3 below for an example of initialization.
  433.  
  434.  
  435. =head1 EXAMPLES
  436.  
  437. =over
  438.  
  439. =item Example 1
  440.  
  441. Giving a struct element a class type that is also a struct is how
  442. structs are nested.  Here, C<timeval> represents a time (seconds and
  443. microseconds), and C<rusage> has two elements, each of which is of
  444. type C<timeval>.
  445.  
  446.     use Class::Struct;
  447.  
  448.     struct( rusage => {
  449.         ru_utime => timeval,  # seconds
  450.         ru_stime => timeval,  # microseconds
  451.     });
  452.  
  453.     struct( timeval => [
  454.         tv_secs  => '$',
  455.         tv_usecs => '$',
  456.     ]);
  457.  
  458.         # create an object:
  459.     my $t = new rusage;
  460.  
  461.         # $t->ru_utime and $t->ru_stime are objects of type timeval.
  462.         # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
  463.     $t->ru_utime->tv_secs(100);
  464.     $t->ru_utime->tv_usecs(0);
  465.     $t->ru_stime->tv_secs(5);
  466.     $t->ru_stime->tv_usecs(0);
  467.  
  468.  
  469. =item Example 2
  470.  
  471. An accessor function can be redefined in order to provide
  472. additional checking of values, etc.  Here, we want the C<count>
  473. element always to be nonnegative, so we redefine the C<count>
  474. accessor accordingly.
  475.  
  476.     package MyObj;
  477.     use Class::Struct;
  478.  
  479.     # declare the struct
  480.     struct ( 'MyObj', { count => '$', stuff => '%' } );
  481.  
  482.     # override the default accessor method for 'count'
  483.     sub count {
  484.         my $self = shift;
  485.         if ( @_ ) {
  486.             die 'count must be nonnegative' if $_[0] < 0;
  487.             $self->{'count'} = shift;
  488.             warn "Too many args to count" if @_;
  489.         }
  490.         return $self->{'count'};
  491.     }
  492.  
  493.     package main;
  494.     $x = new MyObj;
  495.     print "\$x->count(5) = ", $x->count(5), "\n";
  496.                             # prints '$x->count(5) = 5'
  497.  
  498.     print "\$x->count = ", $x->count, "\n";
  499.                             # prints '$x->count = 5'
  500.  
  501.     print "\$x->count(-5) = ", $x->count(-5), "\n";
  502.                             # dies due to negative argument!
  503.  
  504. =item Example 3
  505.  
  506. The constructor of a generated class can be passed a list
  507. of I<element>=>I<value> pairs, with which to initialize the struct.
  508. If no initializer is specified for a particular element, its default
  509. initialization is performed instead. Initializers for non-existent
  510. elements are silently ignored.
  511.  
  512. Note that the initializer for a nested struct is specified
  513. as an anonymous hash of initializers, which is passed on to the nested
  514. struct's constructor.
  515.  
  516.  
  517.     use Class::Struct;
  518.  
  519.     struct Breed =>
  520.     {
  521.         name  => '$',
  522.         cross => '$',
  523.     };
  524.  
  525.     struct Cat =>
  526.     [
  527.         name     => '$',
  528.         kittens  => '@',
  529.         markings => '%',
  530.         breed    => 'Breed',
  531.     ];
  532.  
  533.  
  534.     my $cat = Cat->new( name     => 'Socks',
  535.                         kittens  => ['Monica', 'Kenneth'],
  536.                         markings => { socks=>1, blaze=>"white" },
  537.                         breed    => { name=>'short-hair', cross=>1 },
  538.                       );
  539.  
  540.     print "Once a cat called ", $cat->name, "\n";
  541.     print "(which was a ", $cat->breed->name, ")\n";
  542.     print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";
  543.  
  544. =back
  545.  
  546. =head1 Author and Modification History
  547.  
  548.  
  549. Modified by Damian Conway, 1999-03-05, v0.58.
  550.  
  551.     Added handling of hash-like arg list to class ctor.
  552.  
  553.     Changed to two-argument blessing in ctor to support
  554.     derivation from created classes.
  555.  
  556.     Added classname prefixes to keys in hash-based classes
  557.     (refer to "Perl Cookbook", Recipe 13.12 for rationale).
  558.  
  559.     Corrected behaviour of accessors for '*@' and '*%' struct
  560.     elements.  Package now implements documented behaviour when
  561.     returning a reference to an entire hash or array element.
  562.     Previously these were returned as a reference to a reference
  563.     to the element.
  564.  
  565.  
  566. Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.
  567.  
  568.     members() function removed.
  569.     Documentation corrected and extended.
  570.     Use of struct() in a subclass prohibited.
  571.     User definition of accessor allowed.
  572.     Treatment of '*' in element types corrected.
  573.     Treatment of classes as element types corrected.
  574.     Class name to struct() made optional.
  575.     Diagnostic checks added.
  576.  
  577.  
  578. Originally C<Class::Template> by Dean Roehrich.
  579.  
  580.     # Template.pm   --- struct/member template builder
  581.     #   12mar95
  582.     #   Dean Roehrich
  583.     #
  584.     # changes/bugs fixed since 28nov94 version:
  585.     #  - podified
  586.     # changes/bugs fixed since 21nov94 version:
  587.     #  - Fixed examples.
  588.     # changes/bugs fixed since 02sep94 version:
  589.     #  - Moved to Class::Template.
  590.     # changes/bugs fixed since 20feb94 version:
  591.     #  - Updated to be a more proper module.
  592.     #  - Added "use strict".
  593.     #  - Bug in build_methods, was using @var when @$var needed.
  594.     #  - Now using my() rather than local().
  595.     #
  596.     # Uses perl5 classes to create nested data types.
  597.     # This is offered as one implementation of Tom Christiansen's "structs.pl"
  598.     # idea.
  599.  
  600. =cut
  601.